import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const routes = [
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/auth/LoginView.vue'),
    meta: { 
      requiresGuest: true,
      title: '登录'
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/auth/RegisterView.vue'),
    meta: { 
      requiresGuest: true,
      title: '注册'
    }
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('@/views/DashboardView.vue'),
    meta: { 
      requiresAuth: true,
      title: '仪表板'
    }
  },
  {
    path: '/batches',
    name: 'Batches',
    component: () => import('@/views/batch/BatchListView.vue'),
    meta: { 
      requiresAuth: true,
      title: '茶叶批次'
    }
  },
  {
    path: '/batches/create',
    name: 'CreateBatch',
    component: () => import('@/views/batch/CreateBatchView.vue'),
    meta: { 
      requiresAuth: true,
      roles: ['farmer', 'admin'],
      title: '创建批次'
    }
  },
  {
    path: '/batches/:id',
    name: 'BatchDetail',
    component: () => import('@/views/batch/BatchDetailView.vue'),
    meta: { 
      requiresAuth: true,
      title: '批次详情'
    }
  },
  {
    path: '/batches/:id/edit',
    name: 'EditBatch',
    component: () => import('@/views/batch/CreateBatchView.vue'),
    meta: { 
      requiresAuth: true,
      roles: ['farmer', 'admin'],
      title: '编辑批次'
    }
  },
  {
    path: '/trace',
    name: 'TraceSearch',
    component: () => import('@/views/TraceSearchView.vue'),
    meta: { 
      title: '溯源查询'
    }
  },
  {
    path: '/trace/:batchId',
    name: 'TraceView',
    component: () => import('@/views/TraceView.vue'),
    meta: { 
      title: '溯源详情'
    }
  },
  {
    path: '/statistics',
    name: 'Statistics',
    component: () => import('@/views/StatisticsView.vue'),
    meta: { 
      requiresAuth: true,
      roles: ['farmer', 'logistics', 'merchant', 'admin'],
      title: '数据统计'
    }
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('@/views/user/ProfileView.vue'),
    meta: { 
      requiresAuth: true,
      title: '个人资料'
    }
  },
  {
    path: '/profile/security',
    name: 'Security',
    component: () => import('@/views/user/SecurityView.vue'),
    meta: { 
      requiresAuth: true,
      title: '安全设置'
    }
  },
  {
    path: '/users',
    name: 'Users',
    component: () => import('@/views/admin/UserManageView.vue'),
    meta: { 
      requiresAuth: true,
      roles: ['admin'],
      title: '用户管理'
    }
  },
  {
    path: '/system/settings',
    name: 'SystemSettings',
    component: () => import('@/views/admin/SystemSettingsView.vue'),
    meta: { 
      requiresAuth: true,
      roles: ['admin'],
      title: '系统设置'
    }
  },
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('@/views/NotFoundView.vue'),
    meta: {
      title: '页面未找到'
    }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()
  
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 茶叶溯源系统` : '茶叶溯源系统'
  
  // 检查认证状态
  if (to.meta.requiresAuth) {
    if (!authStore.isAuthenticated) {
      next('/login')
      return
    }
    
    // 检查角色权限
    if (to.meta.roles && !to.meta.roles.includes(authStore.user?.role)) {
      next('/dashboard')
      return
    }
  }
  
  // 已登录用户访问登录/注册页面时重定向到仪表板
  if (to.meta.requiresGuest && authStore.isAuthenticated) {
    next('/dashboard')
    return
  }
  
  next()
})

export default router